package ru.st.selenium.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.FindBys;
import org.openqa.selenium.support.How;

import com.google.common.base.Function;
import com.google.common.cache.Weigher;

import ru.st.selenium.model.Film;

/*
 * Sample page
 * 
 * @author Sebastiano Armeli-Battana
 */
public class HomePage extends Page {

	private static final String FILMS_CSS_SELECTOR = "a[href*='./?go=movie&id=']";

	private final String H1_TAG = "h1";
	
	@CacheLookup
	@FindBy(how = How.TAG_NAME, using = H1_TAG)
	private WebElement h1Element;
	
	@FindBy(css = "a[href*='add']")
	private WebElement addButton;
	
	
	@FindBys(@FindBy(css = FILMS_CSS_SELECTOR))
	private List<WebElement> filmsList;
	
	@FindBy(id = "q")
	private WebElement searchField;
		
	public HomePage(PageManager pageManager) {
		super(pageManager);
	}
	
	public String getH1() {
		return h1Element.getText();
	}
	
	public void clickAddButton() {
	    addButton.click();
	  }
	public void chooseFilmInList() {
		filmsList.get(0).click();
	}
	
	public void enterKeyword(String title) {
		searchField.click();
		searchField.clear();
		searchField.sendKeys(title);
		searchField.sendKeys(Keys.RETURN);
		
		// TERRIBLE HACK
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
		}
		
		filmsList = driver.findElements(By.cssSelector(FILMS_CSS_SELECTOR));
	}
	
	@Override
	public HomePage ensurePageLoaded() {
		wait.until(presenceOfElementLocated(By.id("results")));
	    return this;
	}
	
	public List<Film> getFilms() {
		try {
			List<Film> films = new ArrayList<Film>(filmsList.size());
			for (WebElement element : filmsList){
				Film film = new Film()
					.setId(element.findElement(By.className("movie_box")).getAttribute("id"))
					.setTitle(element.findElement(By.className("title")).getText());
				films.add(film);
			}
			return films;
		} catch (NoSuchElementException e){
			return Collections.emptyList();
		}
	}
}
